// pages/user/applyAfterSale/applyAfterSale.js
var com = require("../../../utils/common.js");
var app = getApp();
var getImgarr = [];//需要过度展示图片
var upimgarr = [];//上传七牛云成功后返给后台的图片
var page_size = 20;
var page_index = 1;//默认页码
var submitOne = true;//限定不可多次提交
var time_id= '';//选择时间段id
var code_id = "";//户号id
var contract_id = "";//户号的合同id
var value_sel=[0, 0, 0];//对应数组下标
var ch_latitude= ''; //当前
var ch_longitude= ''; //当前
Page({

  /**
   * 页面的初始数据
   */

  data: {
    go_right:'../../../images/go_right.png',
    labels: [],//服务类型
    describes: [],//问题原因
    movingShow: false,//移机地址显示
    problemShow: false,//维修问题显示
    inputData:'',//问题具体描述
    isShow: false,
    date: '', //选择日期
    time_list: [],//时间段
    start_time:'',//开始时间
    end_time: '',//结束时间
    time_index: '',
    equipmentDetail: {},//缴费器信息
    imgUrl: [],
    noteMaxLen: 100,
    currentNoteLen: 0,
    add_ress: '',//详细地址
    numberPlate:'',//门牌号
    areaInfo_name: [], //选中地区名称
    area_id_Info: [], //选中的地区id信息
    demolition_type: 2,//拆机类型  1部分 2全部
    demolitionShow: false,//拆机类型显示
    stove_number: '',//炉具眼数
    remarks:'',//备注
    isTextarea: true,//弹出框textarea显隐
    searchshow: false,
    valueName: [],//设置回显选择的地址(name)
  },

  /*** 生命周期函数--监听页面加载*/
  onLoad: function (options) {
    //console.log(options)
    var that = this;
    getImgarr = [];
    upimgarr = [];
    code_id = options.code_id;
    contract_id = options.contract_id;
    that.getEquipmentDetail();
    that.getBussinessType();
    // that.getRangeTime();
    that.getReturnReason();
  },
  onShow: function(){
    submitOne = true;
  },
  /**
 * 生命周期函数--监听页面初次渲染完成
 */
  onReady: function () {
    let that=this;
    that.headid = this.selectComponent("#addre_id"); //引入地址
  },

  // 输入地址
  addressInput(e) {
    var that = this;
    var value = e.detail.value;
    that.setData({
      add_ress: value
    })
  },
  // 输入门牌号
  bindNumberPlate(e){
    var that = this;
    var value = e.detail.value;
    that.setData({
      numberPlate: value
    })
  },
  //选择拆机类型
  demolitionTypeChange(e){
    var that = this;
    var val = e.detail.value;
    that.setData({
      demolition_type: val
    })
  },
  //输入炉具眼数
  bindStoveNumber(e){
    var that = this;
    var value = e.detail.value;
    that.setData({
      stove_number: value
    })
  },
  /**
   * 选择服务类型
   */
  labelClick: function (e) {
    var that = this;
    var labels = that.data.labels;
    var index = e.currentTarget.dataset.labelindex;
    var id = e.currentTarget.dataset.business_type_id;
    // var businessTypeArr = that.data.businessTypeArr;
    var checked = labels[index].checked;
    var up = "labels["+index+"].checked";

    // 服务类型 单选互斥
    for (var i in labels) {
      if (labels[i].data.business_type_id == id) {
        labels[i].checked = true;
      } else {
        labels[i].checked = false;
      }
    }
    that.setData({
      labels: labels
    })

    // 移机
    if(id == 5){
      if (!checked){
        that.setData({
          movingShow: true,
          problemShow: false,
          demolitionShow: false,
          stove_number: '',
        })
      }else{
        that.setData({
          movingShow: false,
          areaInfo_name:[],
          add_ress:'',
          demolitionShow: false,
        })
      }
    }
    // 维修
    if (id == 6) {
      if (!checked) {
        that.setData({
          problemShow: true,
          movingShow: false,
          demolitionShow: false,
        });
      } else {
        that.setData({
          problemShow: false,
          inputData:'',
          imgUrl:[],
          demolitionShow: false,
        });
        getImgarr=[];
        upimgarr=[];
      }
    }
    that.setData({
      [up]: !checked,
    })
    // 拆机
    if (id == 4) {
      if (checked) {
        that.setData({
          problemShow: false,
          inputData: '',
          imgUrl: [],
          movingShow: false,
          areaInfo_name: [],
          add_ress: '',
          demolitionShow: false
        });
        getImgarr = [];
        upimgarr = [];
      }else{
        that.setData({
          demolitionShow: true,
          // demolition_type: 2,
        })
      }
    }
    // 选择拆机类型后不能再选择其他的
    var isRemove = false;
    for(var i in labels){
      if (labels[i].data.business_type_id == 4 && labels[i].checked){
        isRemove = true;
      }
    }
    if (isRemove){
      // for(var i in labels){
      //   if (labels[i].data.business_type_id == 4){
      //     labels[i].checked = true;
      //   }else{
      //     labels[i].checked = false;
      //   }
      // }
      that.setData({
        // labels: labels,
        problemShow: false,
        inputData: '',
        imgUrl: [],
        movingShow: false,
        areaInfo_name: [],
        add_ress: ''
      })
      getImgarr = [];
      upimgarr = [];
    }

  },
  // 选择故障部位
  bindDesChange: function (e) {
    var that = this;
    var describes = that.data.describes;
    var problem_id = e.currentTarget.dataset.problem_id;
    var index = e.currentTarget.dataset.labelindex;
    var checked = describes[index].checked;
    var up = "describes[" + index + "].checked";
    that.setData({
      [up]: !checked
    })
  },
  // 绑定输入问题描述
  inputDes: function(e){
    var value = e.detail.value;
    var len = parseInt(value.length);
    if (len > this.data.noteMaxLen) return;

    this.setData({
      currentNoteLen: len, //当前字数 ,
      inputData: e.detail.value
    });

  },
  // 绑定输入备注
  inputRemark: function(e){
    var that = this;
    that.setData({
      remarks: e.detail.value
    })

  },
  //遮罩时阻止滚动
  myCatchTouch: function () {
    //console.log('stop user scroll it!');
    return;
  },
  // 上传图片
  uploadImages: function(){
    var that = this;
    var num = 3 - getImgarr.length;
    console.log('num:'+num);
    console.log(that.data.imgUrl);
    wx.chooseImage({
      count: num, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        console.log('tempFilePaths:' + tempFilePaths);
        console.log('imgUrl:' + that.data.imgUrl);
        var url = that.data.imgUrl.concat(tempFilePaths);
        for (var k = 0; k < url.length; k++) {
          that.upImg(url[k]);//循环上传图片
        }
      }
    })
  },
  //图片上传
  upImg: function (tempFilePaths) {
    var that = this;
    wx.showLoading({
      title: '上传图片中',
    })
    wx.uploadFile({
      url: app.globalData._url + 'Common/Common/upload',
      filePath: tempFilePaths,
      name: 'file',
      success: function (result) {
        if (result.statusCode !== 200) {
          wx.hideLoading();
          app.showToast('上传失败,请重新上传');
          return
        }
        var data = JSON.parse(result.data);
        if (data.code == 1000) {
          console.log('data.data.all_url:' + data.data.all_url);
          getImgarr.push(data.data.all_url);
          upimgarr.push(data.data.url);
          that.setData({
            imgUrl: getImgarr,
          })
          wx.hideLoading();
        } else {
          wx.hideLoading();
          app.showToast('上传失败,请重新上传');
        }
      },
      fail: function (fail) {
        wx.hideLoading();
        app.showToast('上传失败,请重新上传');
      }
    })
  },
  //删除图片
  detailImg: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.detail;
    getImgarr.splice(index, 1);
    upimgarr.splice(index, 1);
    if (that.data.imgUrl.length == 0) {
      that.setData({
        imgUrl: getImgarr,
      })
    } else {
      that.setData({
        imgUrl: getImgarr,
      })
    }
  },
  //选择日期
  bindDateChange: function (e) {
    //console.log(e.detail.value);
    let that = this;
    let date = e.detail.value;
    that.setData({
      date: date
    })
  },
  //选择时间段
  bindPickerChange: function (e) {
    //console.log(e.detail.value);
    let that = this;
    let time_index = e.detail.value;
    var time_list = that.data.time_list;
    var t_id = time_list[time_index].time_id;
    that.setData({
      time_index: time_index
    })
    time_id = t_id;
  },
  //获取业务类型列表
  getBussinessType(){
    var that = this;
    app.ajax({
      url: 'Common/Common/getBussinessType',
      method: "POST",
      data: { type: 1},
      success: function (res) {
        //console.log(res)
        if (res.data.code == 1000) {
          //console.log(res.data.data);
          var labels = [];
          for(var i in res.data.data){
            labels.push({
              data: res.data.data[i],
              checked: false
            })
          }
          that.setData({
            labels: labels
          })
          console.log(labels);
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //获取预约时间范围
  getRangeTime() {
    var that = this;
    app.ajax({
      url: 'Common/Common/getRangeTime',
      method: "POST",
      data: {},
      success: function (res) {
        //console.log(res)
        if (res.data.code == 1000) {
          //console.log(res.data.data);
          that.setData({
            time_list: res.data.data.time,
            start_time: res.data.data.date.start,
            end_time: res.data.data.date.end,
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //获取故障部位列表
  getReturnReason() {
    var that = this;
    // var business_id = that.data.business_type_id;
    console.log()
    app.ajax({
      url: 'Common/Common/getProblemList',
      method: "POST",
      data: {
        // business_id: business_id
      },
      success: function (res) {
        //console.log(res)
        if (res.data.code == 1000) {
          //console.log(res.data.data);
          var describes=[];
          for(var i in res.data.data){
            describes.push({
              data: res.data.data[i],
              checked: false
            })
          }
          that.setData({
            describes: describes
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },


  //获取缴费器详情
  getEquipmentDetail(){
    var that = this;
    app.ajax({
      url: 'User/Equipmentlists/equipmentDetail',
      method: "POST",
      data: {
        code_id: code_id,
        contract_id: contract_id,
      },
      success: function (res) {
        if (res.data.code == 1000) {
          that.setData({
            equipmentDetail: res.data.data
          })
        } else {
          app.showToast(res.data.message);
        }
      }
    })
  },
  //提交申请
  submitApply(e){
    var that = this;
    console.log('submitOne'+submitOne);
    // if (!submitOne) {
    //   console.log('多次提交');
    //   return;
    // }
    var business_type_id = that.data.business_type_id;
    var labels = that.data.labels;
    var isChecked = false;
    for(var i in labels){
      if( labels[i].checked == true){
        isChecked = true;
        break;
      }
    }
    if (!isChecked) {
      app.showToast('请选择服务类型');
      return false;
    }
    // console.log('日期', that.data.date, '结果', time_id)
    // if (that.data.date == '' || time_id == ''){
    //   app.showToast('预约日期或时间段不能为空', "none", 2000, function () { });
    //   return false;
    // }
    for(var i in labels){
      //移机
      if (labels[i].data.business_type_id == 5 && labels[i].checked){
        if (that.data.areaInfo_name.length == 0) {
          app.showToast('请选择省市区信息', "none", 2000, function () { });
          return false;
        }
        if (that.data.add_ress == '') {
          app.showToast('地址信息不能为空', "none", 2000, function () { });
          return false;
        }
        if (that.data.numberPlate == ''){
          app.showToast('详细地址不能为空',"none",2000,function(){});
          return false;
        }
      }
      //维修
      if (labels[i].data.business_type_id == 6 && labels[i].checked){
        if (that.data.stove_number == '') {
          app.showToast('请输入炉具眼数');
          return false;
        }
        var describes = that.data.describes;
        var isChecked2 = false;
        for (var i in describes){
          if (describes[i].checked == true) {
            isChecked2 = true;
            break;
          }
        }
        if (!isChecked2) {
          app.showToast('请选择故障部位', "none", 2000, function () { });
          return false;
        }
        if (that.data.inputData == '') {
          app.showToast('请详细描述情况', "none", 2000, function () { });
          return false;
        }
      }
      //拆机
      if (labels[i].data.business_type_id == 4 && labels[i].checked){
        if (that.data.demolition_type==1 && that.data.stove_number == '') {
          app.showToast('请输入炉具眼数');
          return false;
        }
      }
    }

    var businessTypeArr =[];
    for(var i in labels){
      if(labels[i].checked){
        businessTypeArr.push(labels[i].data.business_type_id);
      }
    }
    var des_id = [];
    for (var i in describes) {
      if (describes[i].checked == true) {
        des_id.push(describes[i].data.problem_id);
      }
    }
    submitOne = false;
//    app.saveFormId(e.detail.formId);
    // var appointment_date = that.data.date,
    //   appointment_time_id = time_id,
    // var contacts = that.data.equipmentDetail.equipment_lists[0].contact,
    //   contact_number = that.data.equipmentDetail.equipment_lists[0].contact_number,
    var business_id = businessTypeArr,
      problem = that.data.inputData,
      picture = upimgarr,
      problem_key = des_id,
      move_province_code = that.data.area_id_Info[0],//移机省份—移机
      move_city_code = that.data.area_id_Info[1],//移机城市—移机
      move_area_code = that.data.area_id_Info[2],//移机区域—移机
      move_address = that.data.add_ress + '/' + that.data.numberPlate,//移机详细地址—移机
      // move_lng = ch_longitude,//移机地址经度—移机
      // move_lat = ch_latitude,//移机地址纬度—移机
      demolition_type = that.data.demolition_type,//拆机类型
      stove_number = that.data.stove_number,//炉具眼数
      remarks = that.data.remarks;//备注
    app.ajax({
      url: 'User/Work/subWorkOrder',
      method: "POST",
      data: {
        code_id: code_id,
        contract_id: contract_id,
        // appointment_date: appointment_date,
        // appointment_time_id: appointment_time_id,
        // contacts: contacts,
        // contact_number: contact_number,
        business_id: business_id,
        problem: problem,
        picture: picture,
        problem_key: problem_key,
        move_province_code: move_province_code,
        move_city_code: move_city_code,
        move_area_code: move_area_code,
        move_address: move_address,
        // move_lng: move_lng,
        // move_lat: move_lat,
        demolition_type: demolition_type,
        stove_number: stove_number,
        remarks: remarks
      },
      success: function (res) {
        //console.log(res)
        // that.setData({
        //   disabled: false
        // })
        if (res.data.code == 1000) {
          app.showToast(res.data.message);
          setTimeout(() => {
            wx.navigateBack({
              delta:1
            });
            submitOne = true;
          }, 1000);
        } else {
          submitOne=true;
          app.showToast(res.data.message);
        }
      }
    })
  },

  // ======================地址相关==============================================================

  //确定接受
  getSure(data) {
    console.log('确定事件获取地址', data);
    var that = this;
    that.setData({
      areaInfo_name: data.detail.areaName,
      area_id_Info: data.detail.areaId,
      valueName: data.detail.areaName
    })
  },
  //打开地图选择
  openAddress() {
    var that = this;
    this.headid.startAddressAnimation(true);
  },
  // 一下为地址(地图)选择.........................................................................................
  openaddshoose() {
    var that = this;
    wx.chooseLocation({
      success: (res) => {
        console.log('地址选择结果', res);
        ch_longitude = res.longitude;
        ch_latitude = res.latitude;
        that.setData({
          add_ress: res.name
        })
      },
      fail: err => {
        console.log('数据',err.errMsg)
        if (err.errMsg === 'chooseLocation:fail auth deny') {
          wx.showModal({
            title: '提示',
            content: '打开地图,需要您授权位置信息',
            showCancel: false,
            success: data => {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting['scope.userLocation']) {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限成功,再次点击将打开地图',
                      showCancel: false,
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限失败，无法打开地图~',
                      showCancel: false,
                    })
                  }
                },
              })
            }
          })
        }
      }
    });
    //获取地址授权
    // wx.getSetting({
    //   success(res) {
    //     if (!res.authSetting['scope.userLocation']) {
    //       //如果点击的定位图标,提示他未授权
    //       wx.showModal({
    //         content: '你已拒绝授权位置信息,如需重新授权请前往(我的-设置-设置权限)',
    //         showCancel: false,
    //         success: function (res) {
    //           if (res.confirm) {

    //           } else if (res.cancel) {

    //           }
    //         }
    //       })
    //     }
    //   }
    // })
  },
  //取消事件
  closefun() {
    var that = this;
    that.setData({
      pageView: false
    })
  }
})
